/*
 * @Description: 日志管理上下文
 * @Author: Rfan
 * @Date: 2022-09-19 14:08:51
 * @LastEditTime: 2022-09-19 17:48:04
 */

import { createContext, useContext, useEffect, useReducer } from 'react';
import {
  SET_SELECTED_ITEM,
  SET_CURRENT_PAGE,
  PAGE_TYPE_UPLOAD,
  PAGE_TYPE_RESULT,
  SET_ARCHIVE_DATA
} from '../constants';
import { OnlinePreviewReducer } from '../reducers/OnlinePreviewReducer';
import { parsingEEP } from '@/api/archives/archives';
// import fakeData from '../fakeData';

const initialState = {
  // 当前选中的项目
  currentPage: PAGE_TYPE_UPLOAD,

  archiveData: [],

  // -------- 字典 --------
  // 页面状态
  pageType: [
    { id: PAGE_TYPE_UPLOAD, name: 'upload' },
    { id: PAGE_TYPE_RESULT, name: 'result' }
  ]
};

const OnlinePreviewContext = createContext();

const OnlinePreviewContextProvider = (props) => {
  const [state, dispatch] = useReducer(OnlinePreviewReducer, initialState);

  const actions = {
    /**
     * @description: 设置选中的日志类型
     */
    setCurrentPage(data) {
      dispatch({ type: SET_CURRENT_PAGE, data });
    },

    /**
     * @description: 设置表格中选中条目的key
     * @param {*} selectArr
     * @return {*}
     */
    setSelectKey(selectArr) {
      dispatch({ type: SET_SELECTED_ITEM, data: selectArr });
    },

    /**
     * @description: 获取日志列表方法
     * @param {IParsingEEPParams} params 参数
     * @return {Promise}
     */
    parsingEEPFunc(params) {
      return new Promise((resolve, reject) => {
        parsingEEP(params)
          .then((res) => {
            const { data } = res;
            dispatch({ type: SET_ARCHIVE_DATA, data });
            resolve(data);
          })
          .catch((err) => {
            reject(err);
          });
      });
    }
  };

  const filters = {
    stateFilter(id) {
      return state.stateList.find((item) => item.id === id)?.name || '-';
    },
    stateColorFilter(id) {
      return state.stateList.find((item) => item.id === id)?.color || 'blue';
    }
  };

  useEffect(() => {}, []);

  return (
    <OnlinePreviewContext.Provider value={{ ...state, ...actions, ...filters }}>
      {props.children}
    </OnlinePreviewContext.Provider>
  );
};

export const useOnlinePreviewContext = () => {
  return useContext(OnlinePreviewContext);
};

export { OnlinePreviewContext, OnlinePreviewContextProvider };
